<!doctype html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>天天生鲜-购物车</title>
    <link rel="shortcut icon" href="images/logo.png">
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/cart.css">
</head>

<body>
<div id="yc-cart">
    <!-- 头部  -->
    <div class="header_con">
        <div class="header">
            <div class="welcome fl">欢迎来到天天生鲜</div>
            <div class="fr">
                <div class="login_info fl" v-if="onlogin">
                    欢迎：<em>{{loginName}}</em>
                </div>
                <div class="login_btn fl" v-else>
                    <a href="login.html">登录</a>
                    <span> | </span>
                    <a href="register.html">注册</a>
                </div>
                <div class="user_link fl" v-if="onlogin">
                    <span> | </span>
                    <a href="user_center_info.html">用户中心</a>
                    <span> | </span>
                    <a href="cart.html">我的购物车</a>
                    <span> | </span>
                    <a href="user_center_order.html">我的订单</a>
                    <span>|</span>
                    <a href="" @click.prevent="logout()">退出登录</a>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索框-->
    <div class="search_bar clearfix">
        <a href="index.html" class="logo fl"><img src="images/logo.png"></a>
        <div class="search_con fl">
            <form>
                <input type="text" placeholder="搜索商品" class="input_text fl" name="key_words">
                <input type="button" value="搜索" class="input_btn fr">
            </form>
        </div>
        <div class="guest_cart fr">
            <a href="" class="cart_name fl">我的购物车</a>
            <div class="goods_count fl" id="show_count">{{goodsCount}}</div>
        </div>
    </div>

    <!-- 购物车 -->
    <div class="cart_con">
        <h2 class="total_count">全部商品<em>{{goodsCount}}</em>件</h2>
        <div class="cart_list_th clearfix">
            <ul>
                <li class="col01">商品名称</li>
                <li class="col02">商品单位</li>
                <li class="col03">商品价格(元)</li>
                <li class="col04">数量</li>
                <li class="col05">小计</li>
                <li class="col06">操作</li>
            </ul>
        </div>
        <div class="cart_list_td clearfix">
            <ul v-for="(good, index) in goods">
                <li class="col01"><input id="good" type="checkbox" :value="good.cno" @click="select(good.cno)"></li>
                <li class="col02"><img :src="'./'+good.pics"></li>
                <li class="col03">{{good.gname}}<br><em>{{good.price}}元/{{good.weight}}g</em></li>
                <li class="col04">{{good.weight}}</li>
                <li class="col05">{{good.price}}</li>
                <li class="col06">
                    <div class="num_add">
                        <a href="javascript:void(0)" @click="updateNum(index, -1)" class="minus fl">-</a>
                        <input type="text" :value="good.num" class="num_show fl">
                        <a href="javascript:void(0)" @click="updateNum(index, 1)" class="add fl">+</a>
                    </div>
                </li>
                <li class="col07">{{good.price * good.num}}</li>
                <li class="col08"><a href="javascript:;" @click="delGoods(index)">删除</a></li>
            </ul>
        </div>
        <div class="setElements">
            <ul>
                <li class="col01"><input type="checkbox" id="all"></li>
                <li class="col02"><label id="quanxuan" for="all">全选</label></li>
                <li class="col03">合计(不含运费)：
                    <span>￥</span>
                    <em id="totalPrices">{{totalPrice}}</em><br>
                    共计<b id="totalNumbers">{{selectNum}}</b>件商品
                </li>
                <li class="col04"><a href="javascript:void(0)" @click="addOrder">去结算</a></li>
            </ul>
        </div>
    </div>

    <!-- 版权所有 -->
    <div class="footer">
        <div class="foot_link">
            <a href="#">关于我们</a> <span> | </span>
            <a href="#">联系我么</a> <span> | </span>
            <a href="#">招聘人才</a> <span> | </span>
            <a href="#">友情链接</a>
        </div>
        <p>CcpyRight &copy; 2019 衡阳市源辰信息科技有限公司 All Rights Reserverd</p>
        <p>电话：0734-8355998 湘ICP备16015987号</p>
    </div>

</div>


<!--  注意引入顺序 -->
<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/slide.js"></script>
<script src="js/vue.js"></script>
<script src="js/axios.js"></script>
<script src="js/qs.js"></script>
<script>
    Vue.prototype.axios = axios;
    axios.defaults.headers.post['Content-Type'] = 'application/json';
    let begin = "http://localhost:20001/";
    let security = "freshgood-security/";
    let goods = "freshgood-goods/";
    let cart = "freshgood-cart/";
    let order = "freshgood-order/"
    axios.interceptors.request.use(config => {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers.Authorization = token;
            } else {
                config.headers.Authorization = '';
            }
            console.log(token);
            console.log(config);
            return config;
        }, error => {
            return Promise.reject(error);
        }
    );

    let app = new Vue({
        el: "#yc-cart",
        data: {
            onlogin: false,
            outlogin: true,
            loginName: '匿名',
            user: {},
            mno: 0,
            goods: {},
            carts: {},
            goodsCount: 0,
            totalPrice: 0,
            selectCnos: [], //存储选中购物车记录编号
            selectNum: 0, //选择的商品数量和
            selectedGoods: [],
            ono: ''
        },
        mounted: function () {
            //记载页面时，发送请求检查用户是否登录请求  查看购物车
            // axios.all([checkLogin(), findCart()])
            //     .then(axios.spread((rs1, rs2)=>{
            //         if(rs1.data.code === 0){
            //             //说明未登录
            //             this.onlogin = false;
            //             this.outlogin = true;
            //             alert("请先登录！");
            //             location.href="login.html";
            //         }else{
            //             this.user = rs1.data.user;
            //             this.loginName = rs1.data.user.nickName;
            //             this.carts = rs1.data.cartList;
            //             this.mno=rs1.data.user.mno;
            //             this.onlogin = true;
            //             this.outlogin = false;
            //             // this.carts = rs1.data.cartList;
            //             // this.goodsCount = rs1.data.goodsCount;
            //             for (let i = 0; i < this.carts.length; i++) {
            //                 this.goodsCount += this.carts[i].num;
            //             }
            //         }
            //             this.goods = rs2.data;
            //     }));
            axios.all([checkLogin()])
                .then(axios.spread((rs1) => {
                    if (rs1.data.code === 0) {
                        //说明未登录
                        this.onlogin = false;
                        this.outlogin = true;
                        alert("请先登录！");
                        location.href = "login.html";
                    } else {
                        this.user = rs1.data.user;
                        this.loginName = rs1.data.user.nickName;
                        this.carts = rs1.data.cartList;
                        this.mno = rs1.data.user.mno;
                        this.onlogin = true;
                        this.outlogin = false;
                        // this.carts = rs1.data.cartList;
                        // this.goodsCount = rs1.data.goodsCount;
                        for (let i = 0; i < this.carts.length; i++) {
                            this.goodsCount += this.carts[i].num;
                        }
                        axios.all([findCart()])
                            .then(axios.spread((rs2) => {
                                this.goods = rs2.data;
                            }))
                    }
                }));
        },
        methods: {
            logout: function () {
                axios(loginOut()).then(
                    this.onlogin = false,
                    this.outlogin = true,
                )
                location.href = "login.html";
            },
            addOrder: function () {
                this.selectedGoods = this.goods.filter(good => this.selectCnos.includes(good.cno));
                if (this.selectedGoods.length === 0) {
                    alert("请选中结算商品！");
                    return;
                }
                let sum = 0;
                for (let i = 0; i < this.selectedGoods.length; i++) {
                    sum += this.selectedGoods[i].num;
                }
                localStorage.setItem('selectedGoods', JSON.stringify(this.selectedGoods));
                localStorage.setItem('user', JSON.stringify(this.user));
                axios.post(begin + order + "order/addOrder",
                    qs.stringify({
                        cnos: this.selectCnos
                    })
                ).then(rs => {
                    if (rs.data.code !== 0) {
                        this.goodsCount -= sum;
                        this.ono = rs.data.ono;
                        localStorage.setItem('ono', this.ono);
                        location.href = "order.html";
                    } else {
                        alert("下单失败！");
                    }
                })
            },
            delGoods: function (index) {
                let Goods = this.goods[index];
                //删除
                axios.post("cart", qs.stringify({
                    op: 'del', cno: this.goods[index].cno
                })).then(rs => {
                    if (rs.data > 0) {
                        this.goods.splice(index, 1);
                        this.goodsCount -= Goods.num;
                        if (this.selectCnos.includes(Goods.cno)) {
                            this.selectCnos.splice(index, 1);
                        }
                        checkAll.checked = isCheckAll();
                        changeText();
                        gettotalprice();
                    }
                });
            },
            updateNum: function (index, flag) {
                let Goods = this.goods[index];
                if (this.goods[index].num == 1 && flag == -1) {
                    //删除
                    axios({
                        url: begin + cart + "cart/delCart",
                        methods: "get",
                        params: {cno: this.goods[index].cno},
                    }).then(rs => {
                        if (rs.data > 0) {
                            // splice() 方法的参数 index 表示需要删除的元素的索引号，
                            // 1 表示需要删除的元素个数。因此，该代码将会移除名为 goods 的数组中的第 index 项元素。
                            this.goods.splice(index, 1);
                            this.goodsCount--;
                            if (this.selectCnos.includes(Goods.cno)) {
                                this.selectCnos.splice(index, 1);
                            }
                            checkAll.checked = isCheckAll();
                            changeText();
                            gettotalprice();
                        }
                    });
                } else {
                    axios({
                        url: begin + cart + "cart/updateCart",
                        methods: "get",
                        params: {cno: this.goods[index].cno, num: flag},
                    }).then(rs => {
                        if (rs.data > 0) {
                            //修改成功，更新goods中数据
                            this.goods[index].num = this.goods[index].num + flag;
                            this.goodsCount += flag;
                            gettotalprice();
                        }
                    });
                }

            },
            //列表被点击时
            select: function (cno) {
                if (this.selectCnos.includes(cno)) {
                    var index = this.selectCnos.indexOf(cno);
                    this.selectCnos.splice(index, 1);
                    // console.log("remove-true");
                } else {
                    this.selectCnos.push(cno);
                    // console.log("push-true");
                }
                this.selectedGoods = this.goods.filter(good => this.selectCnos.includes(good.cno))
                // console.log('被选中的商品：', this.selectedGoods)
                // console.log(isCheckAll());
                checkAll.checked = isCheckAll();
                changeText();
                gettotalprice();
            },
        },
        computed: {}
    });

    function loginOut() {
        return axios.get(begin + security + "security/freshgood/loginOut");
    }

    //检查用户是否登录
    function checkLogin() {
        return axios.get(begin + security + "security/freshgood/loginCheck");
    }

    //查询购物车
    function findCart() {
        return axios({
            url: begin + cart + "cart/findCart",
            method: "get",
            params: {mno: app.$data.mno}
        });
    }

    const data = app.$data;

    // 检查列表复选框是否全部勾选
    function isCheckAll() {
        return data.goods.length === data.selectCnos.length;
    }

    // 根据全选框状态改变文字
    function changeText() {
        // 如果全选框是勾选的状态，提示文字变为“全不选”
        if (checkAll.checked) {
            document.getElementById("quanxuan").innerHTML = "全不选";
        } else {
            document.getElementById("quanxuan").innerHTML = "全选";
        }
    }

    // 全选input勾选框
    var checkAll = document.getElementById("all");

    function judgeAll() {
        //获取全选是否被选中
        //prop 获取标签的固有属性  attr 自动义的属性
        var flag = $(this).prop("checked");
        if (flag) {
            for (let i = 0; i < data.goods.length; i++) {
                data.selectCnos.push(data.goods[i].cno);
            }
        }
    }

    $("#all").click(function () {
        //获取全选是否被选中
        //prop 获取标签的固有属性  attr 自动义的属性
        var flag = $(this).prop("checked");
        if (flag) {
            for (let i = 0; i < data.goods.length; i++) {
                data.selectCnos.push(data.goods[i].cno);
            }
        } else {
            data.selectCnos.splice(0, data.selectCnos.length);
            // data.selectCnos = [];
        }
        //判断
        $(".cart_list_td ul .col01 input").prop("checked", flag);
        gettotalprice();
        changeText();
    });

    // 计算勾选的商品的总价
    function gettotalprice() {
        // console.log(good);
        var p = 0;
        var n = 0;
        for (var i = 0; i < data.goods.length; i++) {
            for (var j = 0; j < data.selectCnos.length; j++) {
                if (data.selectCnos[j] == data.goods[i].cno) {
                    var quantity = parseInt(data.goods[i].num);
                    var Price = parseFloat(data.goods[i].price);
                    p += Price * quantity;
                    n += quantity;
                }
            }
        }
        // console.log(p+"---"+n);
        // 显示总价
        this.selectNum = n.toFixed(0);
        this.totalPrice = p.toFixed(2);
        document.getElementById('totalPrices').textContent = this.totalPrice;
        document.getElementById('totalNumbers').textContent = this.selectNum;
    }
</script>
</body>
</html>
